<?php
// kouqiang
require_once 'common/GlobalDefine.php';

class WeChatCall{
    function checkSignature() {
        //获取GET的参数
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echoStr = $_GET["echostr"];
        
        //把TOKEN、timestamp和nonce组装到数组里并做排序
        $tmpArr = array(TOKEN, $timestamp, $nonce);
        sort($tmpArr);
    
        //把数组中的元素合并成字符串
        $tmpStr = implode($tmpArr);
    
        //shal加密
        $tmpStr = sha1($tmpStr);
    
        //判断加密后的字符串是否和signature相等
        if($tmpStr == $signature){
            //相等就返回echostr
            echo $echoStr;
            exit(0);
        }
    }
    
    //获取POST数据
    function getPostData()
    {
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];
        return $data;
    }
    
    //响应消息
    public function responseMsg()
    {
        $postStr = $this->getPostData();
        if (!empty($postStr))
        {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            if(!$postObj){
                echo "postObj is NULL"."<BR>";
                exit(0);
            }
            $msgType = trim($postObj->MsgType);
         
        //消息类型分离
            switch ($msgType)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$msgType;
                    break;
            }
        echo $result;
        } else {
            echo "";
            exit;
        }
    }
    
    //接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = array();
				$title1 = "【免费包邮】口腔免费样品申领！口腔医护人员专享福利！";
				$url1 = "http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=507156345&idx=1&sn=c33d99aaa4857b535fa9da6688a80f87#rd";
				$desc1 = "【免费包邮】选择自己喜欢的免费样品，马上领取口腔免费样品！";
				$content[] = array("Title"=>$title1,"Description"=>$desc1,"PicUrl"=>CDN_DOMAIN."2016/0419/06.jpg","Url" => $url1);
			    if ($object->EventKey AND (!empty($object->EventKey)))
				{
					$aid = substr($object->EventKey, 8);
					//$content = '用户扫描带场景值二维码关注 场景值: '.$aid.' '.'open_id: '.$object->FromUserName;
					// TODO: access Mongo DB
					$this->AccessMongoDB($aid, $object->FromUserName);
				}
                break;
            case "unsubscribe":
                break;
            case "SCAN":
                $content = "扫描场景 ".$object->EventKey;
                // 用户曾经关注过，忽略
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "company":
                        $content = array();
                        $content[] = array("Title"=>"上海静乐信息科技有限公司", "Description"=>"上海静乐信息科技有点公司,你值得拥有的合作伙伴!", 
                            "PicUrl"=>QINIU_DOMAIN."Geneler.jpg", "Url" =>MY_HOMEPAGE);
                        break;
                    default:
                        $content = "defalult".$object->EventKey;
                        break;
                }
                break;
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            case "VIEW":
                $content = "跳转链接 ".$object->EventKey;
                break;
            case "MASSSENDJOBFINISH":
                $content = "消息ID：".$object->MsgID."，结果：".$object->Status."，粉丝数：".$object->TotalCount."，过滤："
                    .$object->FilterCount."，发送成功：".$object->SentCount."，发送失败：".$object->ErrorCount;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        if(is_array($content)){
            if (isset($content[0])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }
    
    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        //多客服人工回复模式
        if (strstr($keyword, "您好") || strstr($keyword, "你好") || strstr($keyword, "在吗") || strstr($keyword, "客服")){
            $result = $this->transmitService($object);
        }
        //自动回复模式
        else{
            if (strstr($keyword, "签收")){
                $content = '<a href="http://www.denbox.cn//signGift/index.php" >签收</a>';
            } else if (strstr($keyword, "图片") || strstr($keyword, "呵呵") ){
                $imageUrl = QINIU_DOMAIN."picture/zhangru.jpg";
                $content = $this->returnImage($object, $imageUrl);
            } else if ( strstr($keyword, "报名") || strstr($keyword, "我要样品") || strstr($keyword, "样品") || strstr($keyword, "李施德林") || strstr($keyword, "漱口水")) {
                $content = array();
                $content[] = array(
                    "Title"=>"【免费包邮】口腔免费样品申领！口腔医护人员专享福利！",
                    "Description"=>"【免费包邮】选择自己喜欢的免费样品，马上领取口腔免费样品！",
                    "PicUrl"=>CDN_DOMAIN."2016/0419/06.jpg",
                    "Url"=>'http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=507156345&idx=1&sn=c33d99aaa4857b535fa9da6688a80f87#rd'
                );
            } else if ( strstr($keyword, "时间")) {
                $content = "北京时间:".date("Y-m-d H:i:s",time())."\n\n如需人工客服，请在公众号输入“客服”或“在吗”， 我们的小丫在线与您沟通。";
            } else if ( strstr($keyword, "谢谢")) {
                $content = "亲，客气了，一家人不说两家话，有事再联系!";
            } else if ( strstr($keyword, "收到")) {
                $content = "谢谢，如有任何问题请联系我们!";
            } else if ( strstr($keyword, "回播") || strstr($keyword, "回放") || strstr($keyword, "直播"))  {
                $content = "直播课堂每周四晚8点，每周五中午12点，目前是英文，不支持回播，稍后会有中文字幕,以及回播观看地址。"
                    ."\n\n如需人工客服，请在公众号输入“客服”或“在吗”， 我们的小丫在线与您沟通。";
            }else if (strstr($keyword, "红包")){
                $content = array();
                $content[] = array(
                    "Title"=>"红包",
                    "Description"=>"大年廿八，放假前最后一天上午9:00，不见不散",
                    "PicUrl"=>"http://storage.denbox.cn/DenboxWeChat/AutoReply/GraphicMsg/320x200/RedBag.jpg",
                    "Url"=>'http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=404421529&idx=6&sn=97c09d128426e06bc240759eeb756ffe&scene=0#wechat_redirect'
                );
            } else if (strstr($keyword, "华南展")){
                $content = array();
                $content[] = array(
                    "Title"=>"中华口腔医学会<快递>@您的专属邀请函",
                    "Description"=>"",
                    "PicUrl"=>CDN_DOMAIN."2016/0301/01.jpg",
                    "Url"=>'http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=405613722&idx=1&sn=2c3dd0cc9c9ebd82a5fcf2ceaf8f7f66&scene=0#wechat_redirect'
                );
                $content[] = array(
                    "Title"=>"PEOPLE MOUNTAIN PEOPLE SEA --华南口腔展高露洁现场报道!!",
                    "Description"=>"",
                    "PicUrl"=>CDN_DOMAIN."2016/0301/03.jpg",
                    "Url"=>'http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=405613722&idx=2&sn=1077b803f69e72d23557b9aefeef7505&scene=0#wechat_redirect'
                );
                $content[] = array(
                    "Title"=>"商业创新与口腔行业",
                    "Description"=>"",
                    "PicUrl"=>CDN_DOMAIN."2016/0301/04.jpg",
                    "Url"=>'http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=405613722&idx=3&sn=eb44f877bcd711b870031eefba53fd66&scene=0#wechat_redirect'
                );
                $content[] = array(
                    "Title"=>"3月8日口腔盒子节日大礼！现金红包等你来抢哦~",
                    "Description"=>"",
                    "PicUrl"=>CDN_DOMAIN."2016/0301/05.jpg",
                    "Url"=>'http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=405613722&idx=4&sn=92b962d47359365f610d36d4bb4dfa9b&scene=0#wechat_redirect'
                );
            }else if (strstr($keyword, "扫码")) {
                $content = '<a href="http://www.denbox.cn/southshow/index.php" >扫码</a>';
            } else  if (strstr($keyword, "摇一摇")) {
                $content = '<a href="http://www.denbox.cn/YaoYiYao/index.php" >摇一摇</a>';
            } else if (strstr($keyword, "东北口腔展") || strstr($keyword, "沈阳口腔展")){
                $content = array();
                $content[] = array(
                    "Title"=>"沈阳口腔展高露洁活动信息第二弹！",
                    "Description"=>"2016年3月18-21日第十八届东北口腔展览会高露洁活动信息",
                    "PicUrl"=>"http://storage.denbox.cn/DenboxWeChat/AutoReply/GraphicMsg/320x200/dongbei.jpg",
                    "Url"=>'http://mp.weixin.qq.com/s?__biz=MzAwMTM1NzY1OQ==&mid=406182909&idx=3&sn=39e371d342827ac7157e62b6d44573a7&scene=0#wechat_redirect'
                );
            } else if (strstr($keyword, "测试") || strstr($keyword, "指数工具") || strstr($keyword, "自测") || strstr($keyword, "测一测")){
                $content = '<a href="http://r.xiumi.us/board/v5/27Wit/10642910" >指数工具</a>';
            } else {
                $content = "亲爱的用户，您好。口腔盒子会尽快安排专业客服回复您的问题，谢谢了，亲！"
                    ."\n\n如需人工客服，请在公众号输入“客服”或“在吗”， 我们的小丫在线与您沟通。";
            }

            if(is_array($content)){
                if (isset($content[0]['PicUrl'])){
                    $result = $this->transmitNews($object, $content);
                }else if (isset($content['MusicUrl'])){
                    $result = $this->transmitMusic($object, $content);
                }
            }else{
                $result = $this->transmitText($object, $content);
            }
        }

        return $result;
    }

    
        //接收位置消息
        private function receiveLocation($object)
        {
            $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
            $result = $this->transmitText($object, $content);
            return $result;
        }
    
        //接收语音消息
        private function receiveVoice($object)
        {
            if (isset($object->Recognition) && !empty($object->Recognition)){
                $content = "你刚才说的是：".$object->Recognition;
                $result = $this->transmitText($object, $content);
            }else{
                $content = array("MediaId"=>$object->MediaId);
                $result = $this->transmitVoice($object, $content);
            }
    
            return $result;
        }
    
        //接收视频消息
        private function receiveVideo($object)
        {
            $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
            $result = $this->transmitVideo($object, $content);
            return $result;
        }
    
        //接收链接消息
        private function receiveLink($object)
        {
            $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
            $result = $this->transmitText($object, $content);
            return $result;
        }
    
        //回复文本消息
        private function transmitText($object, $content)
        {
            $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                </xml>";
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
            return $result;
            
            /**
             * <xml> 表示是xml格式
             * <ToUserName><![CDATA[%s]]></ToUserName> 存储微信公众号的ID
             * <FromUserName><![CDATA[%s]]></FromUserName>存储用户ID
             * <CreateTime>%s</CreateTime>存储系统时间
             * <MsgType><![CDATA[text]]></MsgType>存储要发送的消息类型
             * <FuncFlag>0</FuncFlag>是否星标(别管这个）
             * CDATA代表不转义
             * %s表示转换成字符串类型
             * sprintf(baby,$name,$country,...);
             *第一个参数baby表示将要被传送内容的xml格式变量（婴儿），将$name传给baby中第一个出现%s的位置
             *将$country传给第2个出现%s的位置，以此类推
             */
        }
    

        //接收图片消息
        private function receiveImage($object)
        {
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitImage($object, $content);
            return $result;
        }
        //回复图片消息
        private function transmitImage($object, $imageArray)
        {
            $itemTpl = "<Image>
    <MediaId><![CDATA[%s]]></MediaId>
</Image>";
    
            $item_str = sprintf($itemTpl, $imageArray['MediaId']);
    
            $xmlTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            $item_str
            </xml>";
    
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
            return $result;
        }
        
        //回复Url图片
        private function returnImage($object, $imageUrl)
        {
            $xmlTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            <PicUrl><![CDATA[%s]]></PicUrl>
            </xml>";
        
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(),$imageUrl);
            return $result;
        }
    
        //回复语音消息
        private function transmitVoice($object, $voiceArray)
        {
            $itemTpl = "<Voice>
    <MediaId><![CDATA[%s]]></MediaId>
</Voice>";
            $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
            $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[voice]]></MsgType>
                $item_str
                </xml>";
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
            return $result;
        }
    
        //回复视频消息
        private function transmitVideo($object, $videoArray)
        {
            $itemTpl = "<Video>
                <MediaId><![CDATA[%s]]></MediaId>
                <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
                </Video>";
    
            $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
    
            $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[video]]></MsgType>
                $item_str
                </xml>";
    
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
            return $result;
        }
    
        //回复图文消息
        private function transmitNews($object, $newsArray)
        {
            if(!is_array($newsArray)){
                return;
            }
            $itemTpl = "    <item>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
                <PicUrl><![CDATA[%s]]></PicUrl>
                <Url><![CDATA[%s]]></Url>
                </item>";
            $item_str = "";
            foreach ($newsArray as $item){
                $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
            }
            $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[news]]></MsgType>
                <ArticleCount>%s</ArticleCount>
                <Articles>
                $item_str</Articles>
                </xml>";
    
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
            return $result;
        }
    
        //回复音乐消息
        private function transmitMusic($object, $musicArray)
        {
            $itemTpl = "<Music>
                <Title><![CDATA[%s]]></Title>
                <Description><![CDATA[%s]]></Description>
                <MusicUrl><![CDATA[%s]]></MusicUrl>
                <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                </Music>";
    
            $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
    
            $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[music]]></MsgType>
                $item_str
                </xml>";
    
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
            return $result;
        }
    
        //回复多客服消息
        private function transmitService($object)
        {
            $xmlTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[transfer_customer_service]]></MsgType>
                </xml>";
            $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
            return $result;
        }
		
		public function AccessMongoDB($fromAccountToken, $curOpenID)
		{
			// Test mongo DB
			try {
				echo extension_loaded("mongo") ? "loaded\n" : "not loaded \n";
				// test mongo db
				//$connection = new MongoClient();
				$m = new MongoClient( "mongodb://121.41.12.200/" ); // connect to a remote host (default port: 27017)
				//echo ($m === NULL) ? "nullmongo" : "mongon";
				 
				$db = $m->selectDB("test");
				$users = new MongoCollection($db, "users");
			
				$user = $users->findOne(array('openid'=>$curOpenID));
			
				//该用户已关注过，不计入
				if ($user != NULL)
				{
					 
				}
				else
				{			
					$accounts = new MongoCollection($db, "accounts");
					 
					$account = $accounts->findOne(array('token'=>$fromAccountToken));
					if ($account != NULL)
					{
						echo 'add performance';
						// 更新二维码用户的 绩效
						$account['performance']++;
						$accounts->update(array('token'=>$fromAccountToken), $account);
					}
					else
					{
						// 二维码用户非法
						echo 'qr account not existed';
					}
					
					// 写入用户记录
					$userInfo = $this->TryGetUserInfo($curOpenID);
					
					$users->insert(array('openid'=>$curOpenID, 'wechatname'=>$userInfo['nickname'], 'sex'=>$userInfo['sex'], 'address'=>$userInfo['country'].$userInfo['province'].$userInfo['city'], 'subtime'=>time(),'fromAccount'=>$fromAccountToken));
				}
			}
			catch (Exception $e)
			{
				echo "throw exception";
			}
		}
		
		private function GetAccessToken()
		{
			$token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . GenenlerAppID . "&secret=" . GenelerAppSecret;
			$res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
			//echo $res;
			$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
			$accessToken = $result['access_token'];
			 
			echo 'access token: '.$accessToken.'<br/>';
			 
			return $accessToken;
		}
		
		private function GetUserInfo($accessToken, $openid)
		{
			$user_access_url =  "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$accessToken."&openid=".$openid."&lang=zh_CN";
			$res = file_get_contents($user_access_url); //获取文件内容或获取网络请求的内容
			echo $res.'<br/>';
			$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
			 
			return $result;
		}
		
		private function TryGetUserInfo($openid)
		{
			$m = new MongoClient( "mongodb://121.41.12.200/" ); // connect to a remote host (default port: 27017)
			$db = $m->selectDB("test");
		
			$tokenExisted = false;
			$collectionNames = $db->getCollectionNames();
			foreach($collectionNames as $collectionName)
			{
				if ($collectionName == 'wechatToken')
				{
					$tokenExisted = true;
					break;
				}
			}
			 
			if (!$tokenExisted)
			{
				$tokenCollection = $db->createCollection(
						'wechatToken',
						array(
								'capped' => true,
								'size' => 10 * 1024,
								'max' => 10
						)
				);
			}
			else
				$tokenCollection = new MongoCollection($db, 'wechatToken');
			 
			$tokenIt = $tokenCollection->find();
			 
			$accessToken = '';
			if ($tokenIt->count() == 1)
			{
				foreach ($tokenIt as $token)
				{
					echo 'access token: '.$token['access_token'].' timeline: '.$token['timeline'].' current timeline: '.time().'<br/>';
					 
					if ((time() - $token['timeline']) >= 200)
					{
						$accessToken = $this->GetAccessToken();
		
						$oldAccessToken = $token['access_token'];
		
						$token['access_token'] = $accessToken;
						$token['timeline'] = time();
		
						$tokenCollection->update(array('access_token'=>$oldAccessToken), $token);

						echo 'update new access token';
					}
					else
					{
						$accessToken = $token['access_token'];
						echo 'use existed access token';
					}
		
					break;
				}
			}
			else if ($tokenIt->count() == 0)
			{
				$accessToken = $this->GetAccessToken();
		
				$tokenCollection->insert(array('access_token'=>$accessToken, 'timeline'=>time()));
			}
		
			$userInfo =  $this->GetUserInfo($accessToken, $openid);
			echo 'userInfo: nickname: '.$userInfo['nickname'].' sex: '.$userInfo['sex'].' address: '.$userInfo['city'].$userInfo['province'].$userInfo['country'];
		
			return $userInfo;
		}

    }
?>